package com.study.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

/**
 * 请求监听器, 一般用于统计接口调用等, 使用线程防止阻塞请求
 */
@WebListener
public class RequestListener implements ServletRequestListener {

    @Override
    public void requestInitialized(ServletRequestEvent sre) {

        // 系统请求总次数
        Integer count;
        Object reqCount = sre.getServletContext().getAttribute("reqCount");
        if (reqCount == null) {
            count = 0;
        } else {
            count = Integer.valueOf(reqCount.toString());
        }
        count++;
        sre.getServletContext().setAttribute("reqCount", count);

        // 记录特定请求
        HttpServletRequest servletRequest = (HttpServletRequest) sre.getServletRequest();
        String requestURI = servletRequest.getRequestURI();
        String requestURL = servletRequest.getRequestURL().toString();
        String servletPath = servletRequest.getServletPath();

        System.out.println(requestURI);
        System.out.println(requestURL);
        System.out.println(servletPath);
        System.out.println(count);
    }

}
